package com.example.demo.service;

import com.example.demo.mapper.ExpressMapper;
import com.example.demo.mapper.SellerOrderMapper;
import com.example.demo.model.ExpressInfo;
import com.example.demo.model.OrderInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SellerOrderService {
    private static final Logger log = LoggerFactory.getLogger(SellerOrderService.class);

    @Autowired
    private SellerOrderMapper sellerOrderMapper;

    @Autowired
    private ExpressMapper expressMapper;

   
    public List<OrderInfo> getSoldOrders(Integer sellerId, String status) {
        log.info("获取卖家订单列表: sellerId={}, status={}", sellerId, status);
        return sellerOrderMapper.getSoldOrders(sellerId, status);
    }

    public List<OrderInfo> getSoldOrdersComment(Integer sellerId, String status) {
        log.info("获取卖家订单列表: sellerId={}, status={}", sellerId, status);
        return sellerOrderMapper.getSoldOrdersComment(sellerId, status);
    }

    public OrderInfo getOrderDetail(String orderNo, Integer sellerId) {
        log.info("获取订单详情: orderNo={}, sellerId={}", orderNo, sellerId);
        OrderInfo order = sellerOrderMapper.getOrderDetail(orderNo);
        if (order != null && order.getSellerId().equals(sellerId)) {
            return order;
        }
        return null;
    }

    @Transactional
    public int cancelOrder(String orderNo, Integer sellerId, String reason) {
        return sellerOrderMapper.cancelOrder(orderNo, sellerId, reason);
    }

    public String getCancelReason(String orderNo, Integer sellerId) {
        return sellerOrderMapper.getCancelReason(orderNo, sellerId);
    }


    @Transactional
    public boolean ship(ExpressInfo expressInfo, Integer sellerId) {
        try {
            log.info("处理发货请求: expressInfo={}, sellerId={}", expressInfo, sellerId);
            
            // 1. 验证订单是否属于该卖家
            OrderInfo order = sellerOrderMapper.getOrderDetail(expressInfo.getOrderNo());
            if (order == null || !order.getSellerId().equals(sellerId)) {
                log.warn("订单不存在或不属于该卖家: orderNo={}, sellerId={}", expressInfo.getOrderNo(), sellerId);
                return false;
            }

            // 2. 验证订单状态是否为待发货
            if (!"待发货".equals(order.getStatus())) {
                log.warn("订单状态不正确: status={}", order.getStatus());
                return false;
            }

            // 3. 插入快递信息
            expressInfo.setSendTime(new Date());
            expressMapper.insert(expressInfo);

            // 4. 更新订单状态为待收货
            order.setStatus("待收货");
            order.setExpressNo(expressInfo.getExpressNo());
            // 使用正确的日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setUpdateTime(sdf.format(new Date()));
            
            return sellerOrderMapper.updateOrderStatus(order) > 0;
        } catch (Exception e) {
            log.error("发货操作失败", e);
            throw e;
        }
    }

    @Transactional
    public boolean deleteOrder(String orderNo, Integer sellerId) {
        try {
            log.info("删除订单: orderNo={}, sellerId={}", orderNo, sellerId);
            
            OrderInfo order = sellerOrderMapper.getOrderByOrderNo(orderNo);
            if (order == null || !order.getSellerId().equals(sellerId)) {
                log.warn("订单不存在或不属于该卖家");
                return false;
            }

            // 只能删除已完成或已取消的订单
            if (!"已完成".equals(order.getStatus()) && !"已取消".equals(order.getStatus())) {
                log.warn("订单状态不允许删除: status={}", order.getStatus());
                return false;
            }
            
            // 设置卖家删除标记
            order.setSellerDelete(1);
            // 使用正确的日期格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            order.setUpdateTime(sdf.format(new Date()));
            
            return sellerOrderMapper.updateOrderDelete(order) > 0;
        } catch (Exception e) {
            log.error("删除订单失败", e);
            throw e;
        }
    }

    public Map<String, Integer> getOrderCount(Integer sellerId) {
        log.info("获取订单统计: sellerId={}", sellerId);
        List<Map<String, Object>> counts = (List<Map<String, Object>>) sellerOrderMapper.getOrderCount(sellerId);
        Map<String, Integer> result = new HashMap<>();
        
        // 初始化所有状态的计数为0
        result.put("全部", 0);
        result.put("待付款", 0);
        result.put("待发货", 0);
        result.put("待收货", 0);
        result.put("已完成", 0);
        result.put("已取消", 0);

        // 更新实际的计数
        int total = 0;
        for (Map<String, Object> count : counts) {
            String status = (String) count.get("status");
            Integer number = ((Number) count.get("count")).intValue();
            result.put(status, number);
            total += number;
        }
        result.put("全部", total);
        
        return result;
    }


    @Transactional
    public boolean updateRemark(String orderNo, String remark, Integer sellerId) {
        try {
            log.info("更新订单备注: orderNo={}, sellerId={}", orderNo, sellerId);
            
            OrderInfo order = sellerOrderMapper.getOrderByOrderNo(orderNo);
            if (order == null || !order.getSellerId().equals(sellerId)) {
                log.warn("订单不存在或不属于该卖家");
                return false;
            }

            order.setRemark(remark);
            order.setUpdateTime(String.valueOf(new Date()));
            return sellerOrderMapper.updateOrderRemark(order) > 0;
        } catch (Exception e) {
            log.error("更新订单备注失败", e);
            throw e;
        }
    }

    
}